package com.itchen.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itchen.annotation.Log;
import com.itchen.common.Result;
import com.itchen.domain.entity.User;
import com.itchen.domain.login.LoginRequest;
import com.itchen.domain.login.LoginResponse;
import com.itchen.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import com.itchen.utils.JwtTokenUtils;
import com.itchen.utils.PasswordUtil;

import javax.annotation.Resource;

/**
 * 登录 Controller
 */
@Tag(name = "登录", description = "登录相关接口")
@RestController
@RequestMapping("/auth")
public class LoginController {

    @Resource
    private UserService userService;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    @Log(operationType = "登录", operationModule = "系统管理")
    public Result<LoginResponse> login(@RequestBody LoginRequest request) {
        // 查询用户
        User user = userService.getOne(new QueryWrapper<User>()
                .eq("username", request.getUsername()));
        if (user == null) {
            return Result.error("用户名或密码错误");
        }

        // 校验密码
        if (!PasswordUtil.verify(request.getPassword(), user.getPassword())) {
            return Result.error("用户名或密码错误");
        }

        // 生成jwt token
        String token = JwtTokenUtils.genToken(user);

        // 构建登录响应
        LoginResponse response = new LoginResponse();
        response.setUserId(user.getId());
        response.setUsername(user.getUsername());
        response.setNikeName(user.getNikeName());
        response.setRole(user.getRole());
        response.setToken(token);

        return Result.success(response);
    }


    @Operation(summary = "注册")
    @PostMapping("/register")
    @Log(operationType = "新增", operationModule = "用户管理")
    public Result<Boolean> register(@RequestBody User user) {
        //1.先判断是否为空
        if (user == null || user.getUsername() == null || user.getPassword() == null) {
            return Result.error("用户名或密码为空");
        }

        User userBean =  userService.getOne(new QueryWrapper<User>().eq("username", user.getUsername()));

        if ( userBean != null) {
            return Result.error("用户名已存在");
        }

        // 加密密码
        user.setPassword(PasswordUtil.encrypt(user.getPassword()));
        user.setRole("USER");

        return Result.success(userService.save(user));
    }
}